package com.masterclient.app.modules.bridge;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.eoner.baselib.utils.notify.RxBus;
import com.eoner.baselib.utils.sp.SPUtils;
import com.eoner.baselib.utils.status.StatusBarUtil;
import com.eoner.baselibrary.bean.goods.ProductBean;
import com.eoner.baselibrary.utils.TimeUtil;
import com.eoner.common.config.Config;
import com.eoner.commonbean.UrlParam;
import com.eoner.commonbean.popup.CommonPopUpBean;
import com.eoner.managerlibrary.Tools;
import com.eoner.managerlibrary.router.AroutePath;
import com.eoner.managerlibrary.sobot.SobotManager;
import com.eoner.middlelib.eventbus.EventBusManager;
import com.eoner.middlelib.eventbus.event.LoginSuccessEvent;
import com.masterclient.app.BaseActivity;
import com.masterclient.app.R;
import com.masterclient.app.base.ConfirmDialog;
import com.masterclient.app.businessmodule.usermodule.login.index.QuickLoginActivity;
import com.masterclient.app.modules.bridge.contract.BridgeContract;
import com.masterclient.app.modules.bridge.presenter.BridgePresenter;
import com.masterclient.app.modules.chezhubang.SelectMapDialog;
import com.masterclient.app.modules.goods.beans.ShareProductBean;
import com.masterclient.app.modules.search.SearchResultActivity;
import com.masterclient.app.utils.CommonUtil;
import com.masterclient.app.widget.ImageDialog;
import com.masterclient.app.widget.NewcomerProductDialog;
import com.masterclient.app.widget.ShareCommonDialog;
import com.masterclient.app.widget.ShareNewDialog;
import com.masterclient.app.widget.SignInDialog;
import com.masterclient.app.widget.TaskRetainDialog;
import com.masterclient.app.widget.TitlebarView;
import com.google.gson.Gson;
import com.sobot.chat.SobotApi;
import com.sobot.chat.api.enumtype.SobotChatTitleDisplayMode;
import com.sobot.chat.api.model.Information;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import wendu.dsbridge.DWebView;
import wendu.dsbridge.OnReturnValue;

@Route(path = AroutePath.WEB_ACTIVITY)
public class BridgeActivity extends BaseActivity<BridgePresenter> implements BridgeContract.View {

    @BindView(R.id.dwebview)
    DWebView dwebView;
    @BindView(R.id.title_view)
    TitlebarView title_view;
    @BindView(R.id.close)
    ImageView close;
    @BindView(R.id.view_divice)
    View viewDevice;
    @BindView(R.id.bar_view)
    View barView;
    String url;
    String title;
    String mTitle;
    private JsApi jsApi;
    RxBus rxBus;
    Disposable disposable;
    public boolean isInterceptBack = false;
    public boolean isFirstLoad = true;

    public SelectMapDialog dialog;
    public boolean isBdMap = false,isGdMap = false,isTxMap = false;

    @Autowired(name = "routeUrl")
    String routeUrl;

    @Autowired(name = "routeTitle")
    String routeTitle;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBusManager.register(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            DWebView.enableSlowWholeDocumentDraw();
        }
        setContentView(R.layout.activity_bridge);
        ButterKnife.bind(this);

        ARouter.getInstance().inject(this);

        dialog = new SelectMapDialog(this);
        setDialogData();

        List<ProductBean> signList = getIntent().getParcelableArrayListExtra("sign_list");
        if (signList != null && signList.size() > 0) {
            SignInDialog signInDialog = new SignInDialog(this);
            signInDialog.show();
            signInDialog.setData(
                    getIntent().getStringExtra("sign_bupiao"),
                    getIntent().getStringExtra("sign_integral"),
                    getIntent().getStringExtra("sign_coupon"),
                    signList);
        }

        title_view.setRightVisible(View.GONE);
        WebSettings webSettings = dwebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setSupportZoom(true);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setDisplayZoomControls(false);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setAllowFileAccess(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setLoadsImagesAutomatically(true);
        webSettings.setDefaultTextEncodingName("utf-8");
        webSettings.setUserAgentString(webSettings.getUserAgentString() + " app:gm");

        init();
        addListener();
    }

    private void setDialogData(){
        isBdMap = Tools.isAppAvilible(this,"com.baidu.BaiduMap");
        isGdMap = Tools.isAppAvilible(this,"com.autonavi.minimap");
        isTxMap = Tools.isAppAvilible(this,"com.tencent.map");
    }

    public void setDialog(Map<String , String> map){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (isBdMap||isGdMap||isTxMap){
                    dialog.show();
                    dialog.setVisiable(isGdMap,isBdMap,isTxMap);
                    dialog.setData(map.get("lng"),map.get("lat"),
                            map.get("lng"),map.get("lat"),"");
                }else {
                    showToast("请下载高德百度腾讯地图软件进行导航");
                }
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (jsApi != null && "1".equals(jsApi.getIsShowDialog()) && isLogin() && !dwebView.canGoBack()) {
                showBackDialog();
            } else if (jsApi != null && "2".equals(jsApi.getIsShowDialog()) && isLogin() && !dwebView.canGoBack()) {
                showTaskBackDialog();
            } else {
                goBack();
            }
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void addListener() {
        title_view.setOnViewClick(new TitlebarView.onViewClick() {
            @Override
            public void leftClick() {
                if (jsApi != null && "1".equals(jsApi.getIsShowDialog()) && isLogin() && !dwebView.canGoBack()) {
                    showBackDialog();
                } else if (jsApi != null && "2".equals(jsApi.getIsShowDialog()) && isLogin() && !dwebView.canGoBack()) {
                    showTaskBackDialog();
                } else {
                    goBack();
                }
            }

            @Override
            public void rightClick() {
                jsApi.showDialog();
            }
        });

        jsApi.setTitleListener(titleJson -> runOnUiThread(() -> {
            try {
                JSONObject object = new JSONObject(titleJson);
                navTitle = object.optString("itemTitle");
                navIcon = object.optString("itemIcon");
                target = object.optString("target");
                targetID = object.optString("targetID");
                String navTitleTextColor = object.optString("navTextColor");
                title_view.setRightText(navTitle);
                if (!TextUtils.isEmpty(navTitleTextColor))
                    title_view.setRightTextColor(Color.parseColor(navTitleTextColor));

                title_view.setChildClick(viewId -> {
                    switch (viewId) {
                        case R.id.tv_right:
                            CommonUtil.goAnyWhere(BridgeActivity.this,  target, targetID, "", "", "");
                            break;
                        case R.id.iv_right:
                            if (jsApi.getJsBean() == null) {
                                showShareDialog(jsApi.getShareBean());
                            } else {
                                showShareDialog(jsApi.getJsBean());
                            }
                            break;
                        default:
                    }
                });
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }));
    }

    public void removeTitlebarRight() {
        runOnUiThread(() -> {
            navTitle = "";
            target = "";
            if (title_view != null) {
                title_view.setChildClick(null);
                title_view.setRightText("");
                title_view.setRightVisible(View.GONE);
            }
        });
    }

    public boolean isLogin() {
        return !TextUtils.isEmpty(SPUtils.getInstance().getString(Config.CUSTOMER_TOKEN));
    }

    private void showBackDialog() {
        mPresenter.getBackDialogData();
    }

    private void showTaskBackDialog() {
        mPresenter.getTaskBackDialog();
    }

    private void goBack() {
        if (jsApi == null || TextUtils.isEmpty(jsApi.getFinishType())) {
            if (dwebView.canGoBack()) {
                dwebView.goBack();
            } else {
                if (isInterceptBack) {
                    mPresenter.getPopUpData("newer", "", "");
                } else {
                    finish();
                }
            }
        } else {
            finishType();
        }
    }

    ConfirmDialog confirmDialog;

    //type 0 title右键分享 1 h5调用分享
    private void share_click(int type) {
        if (!TextUtils.isEmpty(SPUtils.getInstance().getString(Config.CUSTOMERID))) {
            right_btn_share();
        } else {
            confirmDialog = new ConfirmDialog(BridgeActivity.this, "您暂未登录", "未登录状态的分享将会无法绑定粉丝\n" + "继续分享吗", "继续分享", "去登录", 0);
            confirmDialog.setOnChooseListerner(new ConfirmDialog.OnChooseListerner() {
                @Override
                public void cancel() {
                    confirmDialog.dismiss();
                    right_btn_share();
                }

                @Override
                public void confirm() {
                    confirmDialog.dismiss();
                    startActivitry(QuickLoginActivity.class, new String[][]{{"intentSource", title}});
                }
            });
            confirmDialog.show();
        }

    }

    private void right_btn_share() {
        if (jsApi.getJsBean() == null) {
            showShareDialog(jsApi.getShareBean());
        } else {
            showShareDialog(jsApi.getJsBean());
        }
    }


    String navTitle = "", navIcon, target, targetID;
    ValueCallback<Uri> mFileUploadCallbackLowVersion;
    ValueCallback<Uri[]> mFileUploadCallbackHighVersion;
    int REQUEST_CODE_FILE_PICKER = 100;

    private void init() {

        //TODO:这里对路由进行适配
        if (routeUrl != null && routeUrl.length() > 0) {
            url = routeUrl;
            setAppInfoCookies();
            title = routeTitle;
            mTitle = routeTitle;
        } else {
            url = getBundleString("url");
            setAppInfoCookies();
            title = getBundleString("title");
            mTitle = getBundleString("title");
        }

        if (!TextUtils.isEmpty(title)) {
            title_view.setTitle(title);
        }

        if("dimissTitle".equals(title)){
            barView.setVisibility(View.GONE);
            viewDevice.setVisibility(View.GONE);
        }
        jsApi = new JsApi(this);
        dwebView.addJavascriptObject(jsApi, null);

        dwebView.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                if (!TextUtils.isEmpty(title) && !view.getUrl().contains(title)) {
                    BridgeActivity.this.title = title;
                    title_view.setTitle(title);
                }
                if (isFirstLoad) {
                    mTitle = title;
                    isFirstLoad = false;
                }
                if (!TextUtils.isEmpty(mTitle) && !mTitle.equals(title)) {
                     close.setVisibility(View.GONE);
                } else {
                    close.setVisibility(View.GONE);
                }
            }

            //  Android 3.0 以下
            @SuppressWarnings("unused")
            public void openFileChooser(ValueCallback<Uri> uploadMsg) {
                openFileChooser(uploadMsg, null);
            }

            // Android 3.0以上
            void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
                openFileChooser(uploadMsg, acceptType, null);
            }

            // Androi 4.4以下
            @SuppressWarnings("unused")
            void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                openFileInput(uploadMsg, null, false);
            }

            //  Android 5.0以上
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                if (Build.VERSION.SDK_INT >= 21) {
                    final boolean allowMultiple = fileChooserParams.getMode() == FileChooserParams.MODE_OPEN_MULTIPLE;//是否支持多选
                    openFileInput(null, filePathCallback, allowMultiple);
                    return true;
                } else {
                    return false;
                }
            }

            @SuppressLint("NewApi")
            void openFileInput(final ValueCallback<Uri> fileUploadCallbackFirst, final ValueCallback<Uri[]> fileUploadCallbackSecond, final boolean allowMultiple) {
                //Android 5.0以下版本
                if (mFileUploadCallbackLowVersion != null) {
                    mFileUploadCallbackLowVersion.onReceiveValue(null);
                }
                mFileUploadCallbackLowVersion = fileUploadCallbackFirst;

                //Android 5.0及以上版本
                if (mFileUploadCallbackHighVersion != null) {
                    mFileUploadCallbackHighVersion.onReceiveValue(null);
                }
                mFileUploadCallbackHighVersion = fileUploadCallbackSecond;

                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);

                if (allowMultiple) {
                    if (Build.VERSION.SDK_INT >= 18) {
                        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
                    }
                }
                intent.setType("image/*");
                startActivityForResult(Intent.createChooser(intent, "File Chooser"), REQUEST_CODE_FILE_PICKER);

//                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//                intent.addCategory(Intent.CATEGORY_OPENABLE);
//                intent.setType("image/*");
//                startActivityForResult(Intent.createChooser(intent, "File Chooser"), REQUEST_CODE_FILE_PICKER);

            }

        });

        dwebView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.startsWith("tel:")) {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                    return true;
                }
                if (url.contains("json_info")) {
                    Uri uri = Uri.parse(url);
                    if (uri == null) {
                        return true;
                    }
                    String json_info = uri.getQueryParameter("json_info");
                    Gson gson = new Gson();
                    UrlParam param = gson.fromJson(json_info, UrlParam.class);

                    if ("product".equals(param.getTarget())) {
                        ARouter.getInstance().build(AroutePath.COMMODITY_DETAIL_ACTIVITY)
                                .withString("id", param.getTarget_id())
                                .navigation();
                    } else if ("store".equals(param.getTarget())) {
                        ARouter.getInstance().build(AroutePath.STORE_ACTIVITY).withString("store_id", param.getTarget_id()).navigation();
                    } else if ("concat".equals(param.getTarget())) {
                        Information info = SobotManager.getBaseInfo();
                        //SobotApi.setChatTitleDisplayMode(mContext, SobotChatTitleDisplayMode.ShowFixedText,"中华大师汇");
                        SobotApi.setChatTitleDisplayMode(mContext, SobotChatTitleDisplayMode.Default, "");
                        SobotApi.startSobotChat(BridgeActivity.this, info);
//                        CustomerService.getInstance(mContext).connectService("中华大师汇",null, Config.CUSTOMER);
                    } else if ("searchHot".equals(param.getTarget())) {
                        startActivitry(SearchResultActivity.class, new String[][]{{"keyword", param.getTarget_id()}});
                    }
                    return true;
                } else {
                    return false;
                }
            }
        });
        dwebView.setDownloadListener((url, userAgent, contentDisposition, mimetype, contentLength) -> {
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW,uri);
            startActivity(intent);
        });
        dwebView.loadUrl(url);
        if (TextUtils.isEmpty(url)) {
            showToast("加载数据为空");
        }
//        dwebView.callHandler("getToken",new Object[]{SPUtils.getInstance().getString(Config.CUSTOMER_TOKEN)},new OnReturnValue<Object>(){
//            @Override
//            public void onValue(Object retValue) {
//                Log.d("jsbridge","call succeed,return value is " + retValue);
//            }
//        });
        //注册一些通知H5的方法 askCenterHandler( obj)  type = notice、head、nikeName、wxqr
        rxBus = RxBus.$();
        event_bus_register("notice");
        event_bus_register("head");
        event_bus_register("nikeName");
        event_bus_register("wxqr");
        event_bus_register("cancleLogin");

    }


    //TODO:通知登录成功
    /**
     * 登录成功刷新
     * */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void loginSuccessEvent(LoginSuccessEvent event) {
        if (!TextUtils.isEmpty(SPUtils.getInstance().getString(Config.CUSTOMER_TOKEN))) {
            setAppInfoCookies();
        }
        dwebView.reload();
    }

    private void event_bus_register(String type) {
        rxBus.OnEvent(rxBus.register(type), o -> {
            if ("notice".equals(type) | "head".equals(type) | "nikeName".equals(type) | "wxqr".equals(type)) {
                tast_notify_h5(type);
            } else if ("cancleLogin".equals(type)) {
                cancle_login_notify_h5();
            }
        });
    }

    private void cancle_login_notify_h5() {
        dwebView.callHandler("cancleLogin", new Object[]{"cancleLogin"}, (OnReturnValue<String>) retValue -> {

        });
    }

    private void tast_notify_h5(String type) {
        dwebView.callHandler("taskCenterHandler", new Object[]{type}, (OnReturnValue<String>) retValue -> {

        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (jsApi.isResume()) {
            dwebView.reload();
        }

        if (Config.task_notify) {
            tast_notify_h5("notice");
        }
    }

    @Override
    protected void onDestroy() {
        dwebView.destroy();
        EventBusManager.unRegister(this);
        if (rxBus != null) {
            rxBus.unregister("notice");
            rxBus.unregister("head");
            rxBus.unregister("nikeName");
            rxBus.unregister("wxqr");
            rxBus.unregister("cancleLogin");
            rxBus = null;
        }
        //解决bugly崩溃 下个版本放开
//        if(dwebView != null) {
//            dwebView.getSettings().setBuiltInZoomControls(true);
//            dwebView.setVisibility(View.GONE);
//            long timeout = ViewConfiguration.getZoomControlsTimeout();//timeout ==3000
//            Log.i("time==",timeout+"");
//            new Timer().schedule(new TimerTask() {
//                @Override
//                public void run() {
//                    // TODO Auto-generated method stub
//                    dwebView.destroy();
//                }
//            }, timeout);
//        }

        super.onDestroy();
        jsApi.closeDilog();
        if (disposable != null) disposable.dispose();
    }

    @OnClick({R.id.close})
    void onClick(View v) {
        if (v.getId() == R.id.close) {
            finish();
        }
    }

    void visibleRight() {
        runOnUiThread(() -> title_view.setRightVisible(View.VISIBLE));
    }

    void showShareDialog(JsBean jsBean) {
        ShareCommonDialog vipShareDialog = new ShareCommonDialog(this);
        vipShareDialog.show();
        vipShareDialog.setShareData(jsBean.getSh_title(), jsBean.getSh_url(), jsBean.getSh_sub_title(), jsBean.getSh_icon(), jsBean.getJump_type(), jsBean.getPath(), jsBean.getMini_program_image());
        vipShareDialog.setSData(jsBean.getS_page_type(), jsBean.getS_page_id(), jsBean.getS_product_id(), jsBean.getS_product_name(), jsBean.getS_page_name(), jsBean.getS_page_url());
        vipShareDialog.shareVip(jsBean.getSh_title(), jsBean.getSh_qr_url(), jsBean.getSh_qr_avatar(), jsBean.getSh_qr_poster(), jsBean.getInvite_type());
    }

    private void finishType() {
        switch (jsApi.getFinishType()) {
            case "teaseSuccess":
                jsApi.back("");
                break;
            case "logOffSuccess":
                jsApi.logOutAndGoHome("");
                break;
        }
    }

    void showShareDialog(JsShareBean shareBean) {
        if (shareBean == null) return;
        ShareCommonDialog h5Dialog = new ShareCommonDialog(this, status -> dwebView.callHandler("showSuccess", new Object[]{status == 0}, (OnReturnValue<String>) retValue -> {
        }));
        h5Dialog.show();
        h5Dialog.setShareData(shareBean.getSh_title(), shareBean.getSh_url(), shareBean.getSh_sub_title(), shareBean.getSh_share_image(), shareBean.getJump_type(), shareBean.getPath(), shareBean.getMini_program_image());
        h5Dialog.setSData(shareBean.getS_page_type(), shareBean.getS_page_id(), shareBean.getS_product_id(), shareBean.getS_product_name(), shareBean.getS_page_name(), shareBean.getS_page_url());
        h5Dialog.shareH5(shareBean.getShareType(), shareBean.getSh_max_image(), shareBean.getSh_share_title());
        if (!TextUtils.isEmpty(shareBean.getHide_url_friend_circle())) {
            h5Dialog.setHide_url_friend_circle(shareBean.getHide_url_friend_circle());
        }
    }

    public void setTitle(String title) {
        runOnUiThread(() -> {
            BridgeActivity.this.title = title;
            if (title_view != null) title_view.setTitle(title);
        });
    }

    public void changeTitleStyle(String msg) {
        runOnUiThread(() -> {
            if ("1".equals(msg)) {
                title_view.setLeftDrawable(R.mipmap.white_left);
                title_view.setTitleColor(Color.parseColor("#ffffff"));
                close.setImageResource(R.mipmap.icon_white_finish);
            } else {
                title_view.setLeftDrawable(R.mipmap.point_back_icon);
                title_view.setTitleColor(Color.parseColor("#000000"));
                close.setImageResource(R.mipmap.finish);
            }
        });
    }

    public void changeNavigationBarColor(String alpha, String color) {
        runOnUiThread(() -> {
            if (color != null) {
                title_view.setBackgroundColor(Color.parseColor(color));
                viewDevice.setBackgroundColor(Color.parseColor(color));
                StatusBarUtil.setStatusBarColor(BridgeActivity.this, Color.parseColor(color));
            }
        });
    }

    public void setNavibarHidden(int isHidden) {
        runOnUiThread(() -> {
           if (isHidden == 1){
               barView.setVisibility(View.GONE);
               viewDevice.setVisibility(View.GONE);
           }else {
               barView.setVisibility(View.VISIBLE);
               viewDevice.setVisibility(View.VISIBLE);
           }
        });
    }

    void showGoodsShareDialog(ShareProductBean shareBean) {
        if (shareBean == null) return;
        ShareCommonDialog h5Dialog = new ShareCommonDialog(this, status -> dwebView.callHandler("showSuccess", new Object[]{status == 0}, (OnReturnValue<String>) retValue -> {
        }));
        h5Dialog.show();
        h5Dialog.setSData(shareBean.getS_page_type(), shareBean.getS_page_id(), shareBean.getS_product_id(), shareBean.getS_product_name(), shareBean.getS_page_name(), shareBean.getS_page_url());
        h5Dialog.setShareData(shareBean.getSh_share_title(), shareBean.getSh_url(), shareBean.getSh_sub_title(), shareBean.getSh_share_image());
        h5Dialog.shareGoodsDetail(shareBean);
    }

    void shareNew(JsNewShareBean shareBean) {
        rxBus.OnEvent(Observable.just("!"), o -> new ShareNewDialog(BridgeActivity.this, shareBean, status -> dwebView.callHandler("showSuccess", new Object[]{status == 0}, (OnReturnValue<String>) retValue -> {
        })).show());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (requestCode == 0x7 && resultCode == RESULT_OK) {
            finish();
        }
        if (requestCode == 0) {
            if (intent == null) {
                return;
            }
            //处理返回的data,获取选择的联系人信息
            Uri uri = intent.getData();
            String tel = getPhoneContacts(uri);
            jsApi.gotoH5(tel);
        }
        zhenlv_album_result(requestCode, resultCode, intent);
    }

    private String getPhoneContacts(Uri uri) {
        String name = getPhoneName(uri);
        String phone = "";
        Map<String, String> map = getPhoneContactsList();
        for (Map.Entry<String, String> str : map.entrySet()) {
            if (name.equals(str.getKey())) {
                phone = str.getValue();
            }
        }
        return phone;
    }

    private String getPhoneName(Uri uri) {
        String[] contact = new String[2];
        //得到ContentResolver对象
        ContentResolver cr = getContentResolver();
        //取得电话本中开始一项的光标
        Cursor cursor = cr.query(uri, null, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            //取得联系人姓名
            int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            contact[0] = cursor.getString(nameFieldColumnIndex);
        } else {
            return "";
        }
        return contact[0];
    }

    private Map<String, String> getPhoneContactsList() {
        Map<String, String> map = new HashMap<>();
        ContentResolver cr = getContentResolver();
        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
                null, null, null);
        if (cur.getCount() > 0) {
            while (cur.moveToNext()) {
                String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                    Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + id, null, null);
                    while (phones.moveToNext()) {
                        String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        map.put(name, phoneNumber);
                    }
                    phones.close();
                }
            }
            if (!cur.isClosed()){
                cur.close();
            }
        }
        return map;
    }

    private void zhenlv_album_result(int requestCode, int resultCode, Intent intent) {
        if (requestCode == REQUEST_CODE_FILE_PICKER) {
            if (resultCode == Activity.RESULT_OK) {
                if (intent != null) {
                    //Android 5.0以下版本
                    if (mFileUploadCallbackLowVersion != null) {
                        mFileUploadCallbackLowVersion.onReceiveValue(intent.getData());
                        mFileUploadCallbackLowVersion = null;
                    } else if (mFileUploadCallbackHighVersion != null) {//Android 5.0及以上版本
                        Uri[] dataUris = null;
                        try {
                            if (intent.getDataString() != null) {
                                dataUris = new Uri[]{Uri.parse(intent.getDataString())};
                            } else {
                                if (Build.VERSION.SDK_INT >= 16) {
                                    if (intent.getClipData() != null) {
                                        final int numSelectedFiles = intent.getClipData().getItemCount();
                                        dataUris = new Uri[numSelectedFiles];
                                        for (int i = 0; i < numSelectedFiles; i++) {
                                            dataUris[i] = intent.getClipData().getItemAt(i).getUri();
                                        }
                                    }
                                }
                            }
                        } catch (Exception ignored) {
                        }
                        mFileUploadCallbackHighVersion.onReceiveValue(dataUris);
                        mFileUploadCallbackHighVersion = null;
                    }
                }
            } else {
                //这里mFileUploadCallbackFirst跟mFileUploadCallbackSecond在不同系统版本下分别持有了
                //WebView对象，在用户取消文件选择器的情况下，需给onReceiveValue传null返回值
                //否则WebView在未收到返回值的情况下，无法进行任何操作，文件选择器会失效
                if (mFileUploadCallbackLowVersion != null) {
                    mFileUploadCallbackLowVersion.onReceiveValue(null);
                    mFileUploadCallbackLowVersion = null;
                } else if (mFileUploadCallbackHighVersion != null) {
                    mFileUploadCallbackHighVersion.onReceiveValue(null);
                    mFileUploadCallbackHighVersion = null;
                }
            }
        }
    }

    @Override
    public void showData(List<CommonPopUpBean> dataBean) {
        if (dataBean == null || dataBean.size() < 1) {
            finish();
        } else {
            String lastShowTime = SPUtils.getInstance().getString(Config.DIALOG_SHOW_TIME_NEWCOMER);
            if (TextUtils.isEmpty(lastShowTime) || TimeUtil.time_remain_day(lastShowTime
                    , TimeUtil.get_current_time()) > Long.parseLong(dataBean.get(0).getTrigger_days())) {
                new NewcomerProductDialog(this, dataBean.get(0), () -> finish()).show();
                SPUtils.getInstance().put(Config.DIALOG_SHOW_TIME_NEWCOMER, TimeUtil.get_current_time());
            } else {
                finish();
            }
        }
    }

    @Override
    public void showFailure(String msg) {
        finish();
    }

    @Override
    public void showBackDialogData(BackGuideBean dataBean) {
        if (dataBean.data != null && dataBean.data.isPop) {
            new ImageDialog(title, getActivity(), dataBean.data.imgUrl, dataBean.data.redirectOption, dataBean.data.redirectParam,
                    "", new ImageDialog.OnChooseListerner() {
                @Override
                public void cancel() {
                    jsApi.setIsShowDialog("0");
                    goBack();
                }

                @Override
                public void confirm() {
                    jsApi.setIsShowDialog("1");
                }
            }).show();
        } else {
            goBack();
        }
    }

    @Override
    public void showBackDialogDataFailure(String msg) {
        goBack();
    }

    @Override
    public void showTaskBackDialogData(TaskRetainBean dataBean) {
        if (dataBean.data != null && dataBean.data.rewardItems != null && dataBean.data.rewardItems.size() > 0) {
            TaskRetainDialog taskRetainDialog = new TaskRetainDialog(getActivity());
            taskRetainDialog.show();
            taskRetainDialog.setData(dataBean, new TaskRetainDialog.OnChooseListener() {
                @Override
                public void cancel() {
                    jsApi.setIsShowDialog("0");
                    goBack();
                }

                @Override
                public void confirm() {
                    jsApi.setIsShowDialog("2");
                }
            });
        } else {
            goBack();
        }
    }

    @Override
    public void showTaskBackDialogDataFailure(String msg) {
        goBack();
    }
}
